import { useCommon } from '@/hooks/useCommon.ts'
import { MittEnum } from '@/enums'
import { useMitt } from '@/hooks/useMitt.ts'
import { isDiffNow } from '@/utils/ComputedTime.ts'
import { writeText, writeImage } from '@tauri-apps/plugin-clipboard-manager'
import { detectImageFormat, imageUrlToUint8Array, isImageUrl } from '@/utils/imageUtils'
import { save } from '@tauri-apps/plugin-dialog'
import { useDownload } from '@/hooks/useDownload'
import { useTencentUserStore } from '@/stores/tencentUserStore.ts'
import { useTencentGroupStore } from '@/stores/tencentGroupStore.ts'
import TencentCloudChat, { Message } from '@tencentcloud/chat'
import { useTencentMessageStore } from '@/stores/tencentMessageStore.ts'
import { MessageEncryptor } from '@/hooks/useMessageEncryptor.ts'

MessageEncryptor.IsEncry = true

export const useChatMain = () => {
  const tencentUserStore = useTencentUserStore()
  const tencentGroupStore = useTencentGroupStore()
  const tencentMessageStore = useTencentMessageStore()
  const { removeTag, openMsgSession } = useCommon()
  const { downloadFile } = useDownload()
  /** 滚动条位置 */
  const scrollTop = ref(-1)
  /** 是否是超级管理员 */
  // const isAdmin = computed(() => userInfo?.power === PowerEnum.ADMIN)
  /** 选中的气泡消息 */
  const activeBubble = ref('')
  /** 提醒框标题 */
  const tips = ref()
  /** 是否显示删除信息的弹窗 */
  const modalShow = ref(false)
  /** 需要删除信息的下标 */
  const delIndex = ref('')
  /** 记录历史消息下标 */
  const historyIndex = ref(0)
  /** 当前点击的用户的key */
  const selectKey = ref()

  /** 通用右键菜单 */
  const commonMenuList = ref<OPT.RightMenu[]>([
    {
      label: '转发',
      icon: 'share',
      click: () => {
        // TODO
        window.$message.warning('完善中...')
      }
    },
    {
      label: '收藏',
      icon: 'collection-files',
      click: () => {
        // TODO
        window.$message.warning('完善中...')
      }
    },
    {
      label: '回复',
      icon: 'reply',
      click: (item: Message) => {
        useMitt.emit(MittEnum.REPLY_MEG, item)
      }
    },
    {
      label: '撤回',
      icon: 'corner-down-left',
      click: async (item: Message) => {
        await tencentMessageStore.revokeMessage(item)
      },
      visible: (item: Message) => {
        // 判断当前选择的信息的发送时间是否超过2分钟
        if (isDiffNow({ time: item.time, unit: 'minute', diff: 2 })) return
        // 判断自己是否是发送者
        return item.from === tencentUserStore.myProfile.userID
      }
    }
  ])
  /** 右键消息菜单列表 */
  const menuList = ref<OPT.RightMenu[]>([
    {
      label: '复制',
      icon: 'copy',
      click: async (item: Message) => {
        // 解密消息
        if (item.payload.text.startsWith(MessageEncryptor.MessageEncryptorContentPrefix)) {
          item.payload.text = MessageEncryptor.decrypt(item.payload.text)
        }

        await handleCopy(item.payload.text, true)
      }
    },
    ...commonMenuList.value
  ])
  /** 右键菜单下划线后的列表 */
  const specialMenuList = ref<OPT.RightMenu[]>([
    {
      label: '删除',
      icon: 'delete',
      click: (item: Message) => {
        tips.value = '删除后将不会出现在你的消息记录中，确定删除吗?'
        modalShow.value = true
        delIndex.value = item.ID
      }
    }
  ])
  /** 文件类型右键菜单 */
  const fileMenuList = ref<OPT.RightMenu[]>([
    {
      label: '预览',
      icon: 'preview-open',
      click: (item: Message) => {
        // TODO
        console.log(item)
      }
    },
    ...commonMenuList.value,
    {
      label: '另存为',
      icon: 'Importing',
      click: (item: Message) => {
        // TODO
        console.log(item)
      }
    }
  ])
  /** 图片类型右键菜单 */
  const imageMenuList = ref<OPT.RightMenu[]>([
    {
      label: '复制',
      icon: 'copy',
      click: async (item: Message) => {
        // 对于图片消息，优先使用 url 字段，回退到 content 字段
        const imageUrl = item.payload.imageInfoArray.url
        await handleCopy(imageUrl, true)
      }
    },
    ...commonMenuList.value,
    {
      label: '另存为',
      icon: 'Importing',
      click: async (item: Message) => {
        try {
          const imageUrl = item.payload.imageInfoArray.url
          const suggestedName = imageUrl || 'image.png'

          // 这里会自动截取url后的文件名，可以尝试打印一下
          const savePath = await save({
            filters: [
              {
                name: '图片',
                extensions: ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp']
              }
            ],
            defaultPath: suggestedName
          })

          if (savePath) {
            await downloadFile(imageUrl, savePath)
          }
        } catch (error) {
          console.error('保存图片失败:', error)
          window.$message.error('保存图片失败')
        }
      }
    }
    // {
    //   label: '在文件夹中显示',
    //   icon: 'file2',
    //   click: async (item: MessageType) => {},
    //   visible: (item: MessageType) => {}
    // }
  ])

  /** 右键用户信息菜单(群聊的时候显示) */
  const optionsList = ref<OPT.RightMenu[]>([
    {
      label: '发送信息',
      icon: 'message-action',
      click: async (item: any) => {
        const uid = item.from || item.userID
        await openMsgSession({ userID: uid }, 'user')
      },
      visible: (item: any) => {
        const uid = item.from || item.userID
        return uid !== tencentUserStore.myProfile.userID
      }
    },
    {
      label: 'TA',
      icon: 'aite',
      click: (item: any) => {
        useMitt.emit(MittEnum.AT, item.nick)
      },
      visible: (item: any) => {
        const uid = item.from || item.userID
        return uid !== tencentUserStore.myProfile.userID
      }
    },
    {
      label: '查看资料',
      icon: 'notes',
      click: (item: any, type: string) => {
        // 如果是聊天框内的资料就使用的是消息的key，如果是群聊成员的资料就使用的是uid
        const uid = item.from || item.userID
        useMitt.emit(`${MittEnum.INFO_POPOVER}-${type}`, { uid: uid, type: type })
      }
    },
    {
      label: '修改群昵称',
      icon: 'edit',
      click: () => {},
      visible: (item: any) => {
        const uid = item.from || item.userID
        return uid === tencentUserStore.myProfile.userID
      }
    },
    {
      label: '设为管理员',
      icon: 'people-safe',
      click: async (item: any) => {
        if (tencentGroupStore.currentGroup.groupID) {
          const uid = item.from || item.userID
          tencentGroupStore.setGroupMemberRole({
            groupID: tencentGroupStore.currentGroup.groupID,
            userID: uid,
            role: TencentCloudChat.TYPES.GRP_MBR_ROLE_ADMIN
          })
        }
      },
      visible: (item: any) => {
        const uid = item.from || item.userID
        const selfUid = tencentUserStore.myProfile.userID

        if (uid === selfUid) {
          return false
        }

        if (tencentGroupStore.currentGroup.groupID) {
          const groupMember = tencentGroupStore.groupMemberMap[tencentGroupStore.currentGroup.groupID][uid]

          return (
            tencentGroupStore.currentGroup.ownerID === selfUid &&
            groupMember?.role === TencentCloudChat.TYPES.GRP_MBR_ROLE_MEMBER
          )
        }

        return false
      }
    },
    {
      label: '撤销管理员',
      icon: 'reduce-user',
      click: async (item: any) => {
        if (tencentGroupStore.currentGroup.groupID) {
          const uid = item.from || item.userID
          tencentGroupStore.setGroupMemberRole({
            groupID: tencentGroupStore.currentGroup.groupID,
            userID: uid,
            role: TencentCloudChat.TYPES.GRP_MBR_ROLE_MEMBER
          })
        }
      },
      visible: (item: any) => {
        const uid = item.from || item.userID
        const selfUid = tencentUserStore.myProfile.userID

        if (uid === selfUid) {
          return false
        }

        if (tencentGroupStore.currentGroup.groupID) {
          const groupMember = tencentGroupStore.groupMemberMap[tencentGroupStore.currentGroup.groupID][uid]

          return (
            tencentGroupStore.currentGroup.ownerID === selfUid &&
            groupMember?.role === TencentCloudChat.TYPES.GRP_MBR_ROLE_ADMIN
          )
        }

        return false
      }
    }
  ])

  /** 举报选项 */
  const report = ref<OPT.RightMenu[]>([
    {
      label: '移出本群',
      icon: 'people-delete-one',
      click: async (item: any) => {
        tencentGroupStore.deleteGroupMember({
          groupID: '',
          userIDList: [item.from || item.userID],
          reason: '您已被移出群聊'
        })
      },
      visible: (item: any) => {
        const uid = item.from || item.userID
        const selfUid = tencentUserStore.myProfile.userID

        if (uid === selfUid) {
          return false
        }

        if (tencentGroupStore.currentGroup.groupID) {
          const groupMember = tencentGroupStore.groupMemberMap[tencentGroupStore.currentGroup.groupID][uid]
          const selfGroupInfo = tencentGroupStore.groupMemberMap[tencentGroupStore.currentGroup.groupID][selfUid!]

          // 群主可以移除所有人
          // 管理员只能移除普通成员或游客
          return (
            (selfGroupInfo?.role === TencentCloudChat.TYPES.GRP_MBR_ROLE_ADMIN &&
              (groupMember?.role === TencentCloudChat.TYPES.GRP_MBR_ROLE_MEMBER ||
                groupMember?.role === TencentCloudChat.TYPES.GRP_MBR_ROLE_CUSTOM)) ||
            tencentGroupStore.currentGroup.ownerID === selfUid
          )
        }

        return false
      }
    }
  ])
  /** emoji表情菜单 */
  const emojiList = ref([
    {
      url: '/msgAction/like.png',
      value: 1,
      title: '好赞'
    },
    {
      url: '/msgAction/slightly-frowning-face.png',
      value: 2,
      title: '不满'
    },
    {
      url: '/msgAction/heart-on-fire.png',
      value: 3,
      title: '爱心'
    },
    {
      url: '/msgAction/enraged-face.png',
      value: 4,
      title: '愤怒'
    },
    {
      url: '/emoji/party-popper.webp',
      value: 5,
      title: '礼炮'
    },
    {
      url: '/emoji/rocket.webp',
      value: 6,
      title: '火箭'
    },
    {
      url: '/msgAction/face-with-tears-of-joy.png',
      value: 7,
      title: '笑哭'
    },
    {
      url: '/msgAction/clapping.png',
      value: 8,
      title: '鼓掌'
    },
    {
      url: '/msgAction/rose.png',
      value: 9,
      title: '鲜花'
    },
    {
      url: '/msgAction/bomb.png',
      value: 10,
      title: '炸弹'
    },
    {
      url: '/msgAction/exploding-head.png',
      value: 11,
      title: '疑问'
    },
    {
      url: '/msgAction/victory-hand.png',
      value: 12,
      title: '胜利'
    },
    {
      url: '/msgAction/flashlight.png',
      value: 13,
      title: '灯光'
    },
    {
      url: '/msgAction/pocket-money.png',
      value: 14,
      title: '红包'
    }
  ])

  /**
   * 获取用户选中的文本
   */
  const getSelectedText = (): string => {
    const selection = window.getSelection()
    return selection ? selection.toString().trim() : ''
  }

  /**
   * 检查是否有文本被选中
   */
  const hasSelectedText = (): boolean => {
    const selection = window.getSelection()
    return selection ? selection.toString().trim().length > 0 : false
  }

  /**
   * 清除文本选择
   */
  const clearSelection = (): void => {
    const selection = window.getSelection()
    if (selection) {
      selection.removeAllRanges()
    }
  }

  /**
   * 处理复制事件
   * @param content 复制的内容（作为回退）
   * @param prioritizeSelection 是否优先复制选中的文本
   */
  const handleCopy = async (content: string | undefined, prioritizeSelection: boolean = true) => {
    try {
      let textToCopy = content || ''
      let isSelectedText = false

      // 如果启用了优先选择模式，检查是否有选中的文本
      if (prioritizeSelection) {
        const selectedText = getSelectedText()
        if (selectedText) {
          textToCopy = selectedText
          isSelectedText = true
        }
      }

      // 检查内容是否为空
      if (!textToCopy) {
        window.$message?.warning('没有可复制的内容')
        return
      }

      // 如果是图片
      if (isImageUrl(textToCopy)) {
        try {
          const imageFormat = detectImageFormat(textToCopy)

          // 提示用户正在处理不同格式的图片
          if (imageFormat === 'GIF' || imageFormat === 'WEBP') {
            window.$message?.info(`正在将 ${imageFormat} 格式图片转换为 PNG 并复制...`)
          }

          // 使用 Tauri 的 clipboard API 复制图片（自动转换为 PNG 格式）
          const imageBytes = await imageUrlToUint8Array(textToCopy)
          await writeImage(imageBytes)

          const successMessage = imageFormat === 'PNG' ? '图片已复制到剪贴板' : '图片已转换为 PNG 格式并复制到剪贴板'
          window.$message?.success(successMessage)
        } catch (imageError) {
          console.error('图片复制失败:', imageError)
        }
      } else {
        // 如果是纯文本
        await writeText(removeTag(textToCopy))
        const message = isSelectedText ? '选中文本已复制' : '消息内容已复制'
        window.$message?.success(message)
      }
    } catch (error) {
      console.error('复制失败:', error)
    }
  }

  /**
   * 根据消息类型获取右键菜单列表
   * @param type 消息类型
   */
  const handleItemType = (type: TencentCloudChat.TYPES) => {
    return type === TencentCloudChat.TYPES.MSG_IMAGE || type === TencentCloudChat.TYPES.MSG_FACE
      ? imageMenuList.value
      : type === TencentCloudChat.TYPES.MSG_FILE
        ? fileMenuList.value
        : menuList.value
  }

  /** 删除信息事件 */
  const handleConfirm = () => {
    modalShow.value = false
  }

  /** 点击气泡消息时候监听用户是否按下ctrl+c来复制内容 */
  const handleMsgClick = (item: Message) => {
    activeBubble.value = item.ID
    // 启用键盘监听
    const handleKeyPress = async (e: KeyboardEvent) => {
      if (
        ((e.ctrlKey && e.key === 'c') || (e.metaKey && e.key === 'c')) &&
        item.type === TencentCloudChat.TYPES.MSG_TEXT
      ) {
        // 优先复制用户选中的文本，如果没有选中则复制整个消息内容
        // 对于图片或其他类型的消息，优先使用 url 字段
        const contentToCopy = item.payload.text
        await handleCopy(contentToCopy, true)
        // 取消监听键盘事件，以免多次绑定
        document.removeEventListener('keydown', handleKeyPress)
      }
    }
    // 绑定键盘事件到 document
    document.addEventListener('keydown', handleKeyPress)
  }

  return {
    handleMsgClick,
    handleConfirm,
    handleItemType,
    handleCopy,
    getSelectedText,
    hasSelectedText,
    clearSelection,
    activeBubble,
    historyIndex,
    tips,
    modalShow,
    specialMenuList,
    optionsList,
    report,
    selectKey,
    emojiList,
    commonMenuList,
    scrollTop
  }
}
